package com.zhangxiaofanfan.hotcode.fourth.third;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 *
 * @date 2024-07-13 03:14:13
 * @author zhangxiaofanfan
 */
public class HotCode086 {
    public static void main(String[] args) {
        HotCode086 hotCode = new HotCode086();
        String s = "applepenapple";
        List<String> wordDict = new ArrayList<>(
                List.of("apple","pen")
        );
        System.out.println(hotCode.wordBreak(s, wordDict));
    }

    public boolean wordBreak(String s, List<String> wordDict) {
        wordDict.sort(Comparator.comparingInt(String::length));
        boolean[] dp = new boolean[s.length() + 1];
        dp[0] = true;
        for (int i = 1, wordIndex; i <= s.length(); i++) {
            for (wordIndex = 0; wordIndex < wordDict.size(); wordIndex++) {
                if (strEndWith(s, i - 1, wordDict.get(wordIndex)) && dp[i - wordDict.get(wordIndex).length()]) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.length()];
    }

    public boolean strEndWith(String s, int endIndex, String word) {
        if (word.length() > endIndex + 1) {
            return false;
        }
        for (int i = 0; i < word.length(); i++) {
            if (word.charAt(word.length() - 1 - i) != s.charAt(endIndex - i)) {
                return false;
            }
        }
        return true;
    }

}